package com.frontop.system.modules.attendance.workover.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.frontop.system.modules.attendance.workover.model.AttendanceWorkOver;
import com.frontop.system.modules.attendance.workover.mapper.AttendanceWorkOverMapper;
import com.frontop.system.modules.attendance.workover.service.AttendanceWorkOverService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frontop.system.modules.attendance.workover.vo.AttendanceWorkOverVO;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 考勤-加班记录表 服务实现类
 * </p>
 *
 * @author YangJia
 * @since 2022-01-11
 */
@Service
public class AttendanceWorkOverServiceImpl extends ServiceImpl<AttendanceWorkOverMapper, AttendanceWorkOver> implements AttendanceWorkOverService {
    @Autowired
    AttendanceWorkOverMapper attendanceWorkOverMapper;
    @Override
    public Integer addAttendanceWorkOver(List<JSONObject> dates,String userName) {
        for (JSONObject j : dates){
            Date date = j.getDate("value");
            AttendanceWorkOver attendanceWorkOver = new AttendanceWorkOver();
            attendanceWorkOver.setGoWorkTime(date);
            //用户名
            attendanceWorkOver.setUserName(userName);
            //验证周六周末
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            Integer isWeekdays = cal.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY||cal.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY ? 1:0;
            attendanceWorkOver.setIsWeekdays(isWeekdays);
            attendanceWorkOver.setStatus(1);
            //添加入库
            save(attendanceWorkOver);
        }
        return dates.size();
    }

    @Override
    public List<JSONObject> getAllWorkOverByUserName(String userName) {
        return attendanceWorkOverMapper.getAllWorkOverByUserName(userName);
    }

    @Override
    public Integer addAttendanceWorkOverByExcel(MultipartFile file,String userName) {
        ArrayList<ArrayList<String>> row = new ArrayList<>();
        //获取文件名称
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);
        try {
            //获取输入流
           InputStream in = file.getInputStream();
            //判断excel版本
           Workbook workbook = null;
            if (fileName.endsWith("xlsx")) {
                workbook = new XSSFWorkbook(in);
            } else {
                workbook = new HSSFWorkbook(in);
            }

            //获取第一张工作表
            Sheet sheet = workbook.getSheetAt(0);
            SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy/MM/dd");
            SimpleDateFormat simpleTime = new SimpleDateFormat("HH:mm");
            //从第5行开始获取
            for (int i = 4; i < sheet.getPhysicalNumberOfRows(); i++) {
                //循环获取工作表的每一行
                Row sheetRow = sheet.getRow(i);
                AttendanceWorkOver attendanceWorkOver = new AttendanceWorkOver();
                attendanceWorkOver.setUserName(userName);
                try {
                    Date workDate = simpleDate.parse(sheetRow.getCell(0).getStringCellValue());
                    attendanceWorkOver.setWorkDate(workDate);
                    if(!sheetRow.getCell(7).getStringCellValue().equals("未打卡")){
                        attendanceWorkOver.setComeWorkTime(simpleTime.parse(sheetRow.getCell(7).getStringCellValue()));
                    }
                    if(!sheetRow.getCell(8).getStringCellValue().equals("未打卡")){
                        String goWorkTime = sheetRow.getCell(8).getStringCellValue();
                        //验证是否是次日下班
                        if(goWorkTime.contains("次日")){
                            attendanceWorkOver.setIsNextDay(1);
                            attendanceWorkOver.setGoWorkTime(simpleTime.parse(goWorkTime.substring(2,goWorkTime.length())));
                        }else {
                            attendanceWorkOver.setGoWorkTime(simpleTime.parse(goWorkTime));
                        }
                    }
                    //工作时长
                    try {
                        attendanceWorkOver.setWorkingHours(Double.parseDouble(sheetRow.getCell(11).getStringCellValue()));
                    }catch (Exception e){
                        attendanceWorkOver.setWorkingHours(0.0);
                    }
                    //验证周六周末
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(workDate);
                    Integer isWeekdays = cal.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY||cal.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY ? 1:0;
                    attendanceWorkOver.setIsWeekdays(isWeekdays);
                    //状态
                    attendanceWorkOver.setStatus(1);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                try {
                    save(attendanceWorkOver);
                }catch (Exception e){
                    //如果添加失败 说明存在相同日期，将数据删除在添加
                    Map<String,Object> map = new HashMap<>();
                    map.put("user_name",userName);
                    map.put("work_date",sheetRow.getCell(0).getStringCellValue());
                    removeByMap(map);
                    save(attendanceWorkOver);
                }
                System.out.println(JSONObject.toJSONString(attendanceWorkOver));
                //关闭资源
                workbook.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Page<AttendanceWorkOver> selectAttendanceWorkOverPage(Page<AttendanceWorkOver> page, AttendanceWorkOverVO vo) {
        return attendanceWorkOverMapper.selectAttendanceWorkOverPage(page,vo);
    }

    @Override
    public Page<AttendanceWorkOver> selectWorkeOverAbnormal(Page<AttendanceWorkOver> page, AttendanceWorkOverVO vo) {
        return attendanceWorkOverMapper.selectWorkeOverAbnormal(page,vo);
    }

    @Override
    public Integer updateStatus(Integer id) {
        return attendanceWorkOverMapper.updateStatus(id);
    }

    @Override
    public JSONObject selectWorkeOverStatistics(Map<String, Object> map) {
        return attendanceWorkOverMapper.selectWorkeOverStatistics(map);
    }


    /**
     * 返回指定和当前时间相差多少天
     * @param date
     * @return
     */
    public Long dayXc(Date date){
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long days = null;
        try {
            Date currentTime = dateFormat.parse(dateFormat.format(new Date()));//现在系统当前时间

            long diff = currentTime.getTime() - date.getTime();

            days = diff / (1000 * 60 * 60 * 24);

        } catch (ParseException e) {

            e.printStackTrace();

        }
        return days;
    }

}